package com.app.couponsharelife.manage;
import android.annotation.TargetApi;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.StrictMode;

import androidx.multidex.MultiDex;

import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.alibaba.baichuan.android.trade.AlibcTradeSDK;
import com.alibaba.baichuan.android.trade.callback.AlibcTradeInitCallback;
import com.alibaba.wireless.security.jaq.JAQException;
import com.alibaba.wireless.security.jaq.SecurityInit;
import com.bilibili.boxing.BoxingMediaLoader;
//import com.kepler.jd.Listener.AsyncInitListener;
//import com.kepler.jd.login.KeplerApiManager;
import com.app.couponsharelife.R;
import com.app.couponsharelife.utils.BoxingGlideLoader;
import com.mob.MobSDK;
import com.taobao.sophix.PatchStatus;
import com.taobao.sophix.SophixManager;
import com.tencent.bugly.Bugly;
import com.tencent.bugly.beta.Beta;
import com.tencent.bugly.beta.UpgradeInfo;
import com.tencent.bugly.beta.ui.UILifecycleListener;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tencent.smtt.sdk.QbSdk;
import com.tencent.tinker.entry.DefaultApplicationLike;

import java.math.BigDecimal;

import cn.jpush.android.api.JPushInterface;
import io.reactivex.plugins.RxJavaPlugins;

/**
 * Created by guluwa on 2018/6/1.
 */
public class MyApplication extends DefaultApplicationLike {
    private static Context mContext;
    private static IWXAPI api;
    public MyApplication(Application application, int tinkerFlags,
                         boolean tinkerLoadVerifyFlag, long applicationStartElapsedTime,
                         long applicationStartMillisTime, Intent tinkerResultIntent) {
        super(application, tinkerFlags, tinkerLoadVerifyFlag, applicationStartElapsedTime, applicationStartMillisTime, tinkerResultIntent);
    }
    @Override
    public void onCreate() {
        super.onCreate();
        mContext=getApplication();
        // queryAndLoadNewPatch不可放在attachBaseContext 中，否则无网络权限，建议放在后面任意时刻，如onCreate中
//        SophixManager.getInstance().queryAndLoadNewPatch();
        //CrashReport
//        CrashReport.initCrashReport(mContext, "9d85f6980d", false);

        //JPush
//        JPushInterface.setDebugMode(true);// 设置开启日志,发布时请关闭日志
//        JPushInterface.init(this);// 初始化 JPush

        initBoxing();
        initAlibc();
        registToWX();
        initSharePic();
        handleError();
        initJDSDK();
        Beta.autoInit = true;
        initBuglyUpDateDialog();
        Bugly.init(getApplication(), "9db67f2d80", true);
        //搜集本地tbs内核信息并上报服务器，服务器返回结果决定使用哪个内核。
        QbSdk.PreInitCallback cb = new QbSdk.PreInitCallback() {

            @Override
            public void onViewInitFinished(boolean arg0) {
                // TODO Auto-generated method stub
                //x5內核初始化完成的回调，为true表示x5内核加载成功，否则表示x5内核加载失败，会自动切换到系统内核。
                //Log.d("app", " onViewInitFinished is " + arg0);
            }

            @Override
            public void onCoreInitFinished() {
                // TODO Auto-generated method stub
            }
        };
        //x5内核初始化接口
        QbSdk.initX5Environment(getApplication(),  cb);
        MobSDK.init(getApplication());
        //极光
        JPushInterface.setDebugMode(false);
        JPushInterface.init(mContext);
    }

    /**
     * RxJava2 当取消订阅后(dispose())，RxJava抛出的异常后续无法接收(此时后台线程仍在跑，可能会抛出IO等异常),全部由RxJavaPlugin接收，需要提前设置ErrorHandler
     * 详情：http://engineering.rallyhealth.com/mobile/rxjava/reactive/2017/03/15/migrating-to-rxjava-2.html#Error Handling
     */
    private void handleError() {
        RxJavaPlugins.setErrorHandler(throwable -> Log.e("error", throwable.toString()));
    }
    private void initSharePic() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
            StrictMode.setVmPolicy(builder.build());
        }
    }

    private void initBoxing() {
        BoxingGlideLoader loader = new BoxingGlideLoader();
        BoxingMediaLoader.getInstance().init(loader);
    }

    private void initAlibc() {
//        AlibcTradeCommon.turnOnDebug();
//        AlibcTradeBiz.turnOnDebug();
        //初始化
        try {
            AlibcTradeSDK.asyncInit(getApplication(), new AlibcTradeInitCallback() {

                private static final long serialVersionUID = 1377717152275794205L;

                @Override
                public void onSuccess() {
                    //System.out.println("alibc 初始化成功");
                }

                @Override
                public void onFailure(int code, String msg) {
                    //System.out.println("alibc 初始化失败,错误码=" + code + " / 错误消息=" + msg);
                }
            });
            if (SecurityInit.Initialize(mContext) == 0) {
                //Log.e("yjk", "聚安全初始化成功");
            } else {
                //Log.e("yjk", "聚安全初始化失败");
            }
        } catch (JAQException e) {
            //Log.e("yjk", "errorCode =" + e.getErrorCode());
        }
    }

    private void registToWX() {
        //AppConst.WEIXIN.APP_ID是指你应用在微信开放平台上的AppID，记得替换。
        api = WXAPIFactory.createWXAPI(getApplication(), Contacts.WECHAT_APP_ID, false);
        // 将该app注册到微信
        api.registerApp(Contacts.WECHAT_APP_ID);
    }

    @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    @Override
    public void onBaseContextAttached(Context base) {
        super.onBaseContextAttached(base);
        // you must install multiDex whatever tinker is installed!
        MultiDex.install(base);

        // 安装tinker
        // TinkerManager.installTinker(this); 替换成下面Bugly提供的方法
        Beta.installTinker(this);
    }

    @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    public void registerActivityLifecycleCallback(Application.ActivityLifecycleCallbacks callbacks) {
        getApplication().registerActivityLifecycleCallbacks(callbacks);
    }
    //初始化京东SDK
    private void initJDSDK(){
//        KeplerApiManager.asyncInitSdk(getApplication(), "4fdd3c891df443b5b0fee3df9a2c95d7", "3431ae3764a34f78b0b924903a2a438d",
//                new AsyncInitListener() {
//                    @Override
//                    public void onSuccess() {
//                        //Log.e("Kepler", "Kepler asyncInitSdk onSuccess ");
//                    }
//                    @Override
//                    public void onFailure() {
//                        //Log.e("Kepler",
//                                //"Kepler asyncInitSdk 授权失败，请检查lib 工程资源引用；包名,签名证书是否和注册一致");
//
//                    }
//                });
    }
    private void initHotFix() {

        String appVersion = "1.0.0";

        try {
            appVersion = getApplication().getPackageManager().getPackageInfo(getApplication().getPackageName(), 0).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        // initialize必须放在attachBaseContext最前面，初始化代码直接写在Application类里面，切勿封装到其他类。
        SophixManager.getInstance().setContext(getApplication())
                .setAppVersion(appVersion)
                .setPatchLoadStatusStub((mode, code, info, handlePatchVersion) -> {
                    // 补丁加载回调通知
                    if (code == PatchStatus.CODE_LOAD_SUCCESS) {
                        // 表明补丁加载成功
                        //Log.e("error", "CODE_LOAD_SUCCESS");
                    } else if (code == PatchStatus.CODE_LOAD_RELAUNCH) {
                        // 表明新补丁生效需要重启. 开发者可提示用户或者强制重启;
                        // 建议: 用户可以监听进入后台事件, 然后应用自杀
                        //Log.e("error", "CODE_LOAD_RELAUNCH");
                    } else if (code == PatchStatus.CODE_LOAD_FAIL) {
                        // 内部引擎异常, 推荐此时清空本地补丁, 防止失败补丁重复加载
                        // SophixManager.getInstance().cleanPatches();
                        //Log.e("error", "CODE_LOAD_FAIL");
                    } else {
                        // 其它错误信息, 查看PatchStatus类说明
                        //Log.e("error", code + "");
                    }
                }).initialize();
    }
    private void initBuglyUpDateDialog(){
        Beta.upgradeDialogLayoutId = R.layout.dialog_bugly_update;
        Beta.tipsDialogLayoutId = R.layout.dialog_bugly_update;
        Beta.upgradeDialogLifecycleListener = new UILifecycleListener<UpgradeInfo>(){
            @Override
            public void onCreate(Context context, View view, UpgradeInfo upgradeInfo) {
                TextView tvTitle=view.findViewById(R.id.tvVersionsName);
                TextView tvInfo=view.findViewById(R.id.tvPackgeSize);
                tvTitle.setText("v"+upgradeInfo.versionName);
                Long fileSize=upgradeInfo.fileSize;
                if (fileSize>0){
                    BigDecimal bigDecimal=new BigDecimal(fileSize);
                    bigDecimal=bigDecimal.divide(new BigDecimal(1024)).divide(new BigDecimal(1024));
                    String size="大小:"+bigDecimal.setScale(2, BigDecimal.ROUND_DOWN)+"m";
                    tvInfo.setText(size);
                }

            }

            @Override
            public void onStart(Context context, View view, UpgradeInfo upgradeInfo) {

            }

            @Override
            public void onResume(Context context, View view, UpgradeInfo upgradeInfo) {

            }

            @Override
            public void onPause(Context context, View view, UpgradeInfo upgradeInfo) {

            }

            @Override
            public void onStop(Context context, View view, UpgradeInfo upgradeInfo) {

            }

            @Override
            public void onDestroy(Context context, View view, UpgradeInfo upgradeInfo) {

            }
        };
    }
    public static Context getContext() {
        return mContext;
    }

    public static IWXAPI getWXAPI() {
        return api;
    }
}
